#include "TcpServerThreadPool.h"

void TcpServerThreadPool::deal_client(int fd) {
    // s_write(fd,);
    // s_read(fd,...);
}

TcpServerThreadPool::TcpServerThreadPool(shared_ptr<FileOpt> fileOpt,const string& ip, int l_port,int l_link_max, int& ret)
: port(l_port)
, server_ip(ip)
, link_max(l_link_max)
, objcreat_errflag(0)
, m_fileOpt(fileOpt)
{

    int opt = 1;
    // 创建套接字
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        printf("%s:%d\n", __FUNCTION__, __LINE__);
        objcreat_errflag = 1;
        ret = 1;// socket error;
    }
    // ssock=server_fd;
    link_success = 0;
        // 设置套接字选项，允许端口重用
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {

        printf("%s:%d\n", __FUNCTION__, __LINE__);
        objcreat_errflag = 1;
        ret = 2;// socket error;
    }
    address.sin_family = AF_INET;
    // address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(port);
    // 将IP地址从字符串转换为网络字节序
    if(inet_pton(AF_INET, server_ip.c_str(), &address.sin_addr)<=0) {
        perror("Invalid address/Address not supported");
        ret = 5;// socket error;
    }
    // 绑定套接字到地址
    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address))<0) {

        printf("%s:%d\n", __FUNCTION__, __LINE__);
        objcreat_errflag = 1;
        ret = 3;// socket error;
    }

    // 开始监听，最大连接数为5
    if (listen(server_fd, link_max) < 0) {
        printf("%s:%d\n", __FUNCTION__, __LINE__);
        objcreat_errflag = 1;
        ret = 4;// socket error;
    }
}

int TcpServerThreadPool::wait_tcp_link(void)
{
    //int new_socket;
    printf("Waiting for connection...\n");
    if(objcreat_errflag == 1)
    {
        printf("%s:%d\n", __FUNCTION__, __LINE__);
      return -1;

    }
    size_t addrlen = sizeof(address);
    int new_socket = 0;
    if((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0) {
                perror("Accept failed");
            printf("%s:%d\n", __FUNCTION__, __LINE__);
                    return -1;
    }
    link_success = 1;
    printf("Connection accepted\n");
    m_threadPool_.AddTask([this, new_socket]{deal_client(new_socket);});
    return new_socket;
}

int TcpServerThreadPool::s_read(int socket,char* buffer,int len)
{
    return m_fileOpt->f_read(socket,buffer,len);
}

int TcpServerThreadPool::s_write(int socket,char* buffer,int len)
{
    return m_fileOpt->f_write(socket,buffer,len);
}
TcpServerThreadPool::~TcpServerThreadPool()
{ 
    close(server_fd);
    link_success = 0;
}